<template>
  <div style="font-size: 14px">
    <!-- 问题详情弹窗 -->
    <el-drawer v-model="dialogVisible" title="问题详情" direction="rtl" size="1080">
      <div v-loading="loading">
        <div class="btns" v-if="details.statusCode != 'problem_closed'">
          <span>操作：</span>
          <el-button type="primary" @click="showProblemAssignmentMask">问题指派</el-button>
          <el-button type="primary" v-if="details.technicianName" @click="showTaskCxzp">任务重新指派</el-button>
          <el-button type="primary" v-if="details.knownError" @click="cancelKnownError">取消已知错误标记</el-button>
          <el-button type="primary" v-else @click="markKnownError">标记为已知错误</el-button>
          <el-button type="primary" v-if="details.flowStart == false && details.technicianName != ''" @click="showkqlc">
            开启流程
          </el-button>
          <el-button type="primary" v-for="item in processDetailData.outcomes" :key="item" @click="processOutcome(item)">
            {{ item }}
          </el-button>
          <!-- <el-dropdown>
		    <div class="el-dropdown-link">
		      <el-button type="primary" plain>
		        <span>更多操作</span>
		        <el-icon class="el-icon--right">
		          <arrow-down />
		        </el-icon>
		      </el-button>
		    </div>
		    <template #dropdown>
		      <el-dropdown-menu>
		        <div >
		          <el-dropdown-item v-if="details.processKey" @click="seeFlowChart">流程跟踪</el-dropdown-item>
		        </div>
		      </el-dropdown-menu>
		    </template>
		  </el-dropdown> -->
        </div>
        <div class="btns" v-if="details.statusCode == 'problem_closed'">
          <span>操作：</span>
          <el-button type="primary" @click="reStart">流程重新开启</el-button>
        </div>

        <div class="title">基本信息</div>
        <div class="table-data-box">
          <div class="data-cell row">
            <span class="label">标题</span>
            <span class="content">{{ details.etitle }}</span>
          </div>
          <div class="data-cell row">
            <span class="label">描述</span>
            <div class="content" v-html="details.edesc"></div>
          </div>
          <div class="data-cell">
            <span class="label">所属客户</span>
            <span class="content">{{ details.companyName }}</span>
          </div>
          <div class="data-cell">
            <span class="label">问题编号</span>
            <span class="content">{{ details.ecode }}</span>
          </div>
          <div class="data-cell">
            <span class="label">问题分类</span>
            <span class="content">{{ details.categoryName }}</span>
          </div>
          <div class="data-cell">
            <span class="label">状态</span>
            <span class="content">{{ details.statusName }}</span>
          </div>
          <div class="data-cell">
            <span class="label">优先级</span>
            <div class="content">
              <span
                v-if="details.priorityColor"
                :style="{ background: details.priorityColor }"
                style="padding: 0 8px; color: #ffffff"
              >
                {{ details.priorityName }}
              </span>
              <span v-else>{{ details.priorityName }}</span>
            </div>
          </div>
          <div class="data-cell">
            <span class="label">影响</span>
            <div class="content">
              <span
                v-if="details.effectRangeColor"
                :style="{ background: details.effectRangeColor }"
                style="padding: 0 8px; color: #ffffff"
              >
                {{ details.effectRangeName }}
              </span>
              <span v-else>{{ details.effectRangeName }}</span>
            </div>
          </div>
          <div class="data-cell">
            <span class="label">紧急度</span>
            <div class="content">
              <span
                v-if="details.seriousnessColor"
                :style="{ background: details.seriousnessColor }"
                style="padding: 0 8px; color: #ffffff"
              >
                {{ details.seriousnessName }}
              </span>
              <span v-else>{{ details.seriousnessName }}</span>
            </div>
          </div>
          <div class="data-cell">
            <span class="label">期望完成日期</span>
            <span class="content">{{ details.overdueTime }}</span>
          </div>
          <div class="data-cell">
            <span class="label">实际结束时间</span>
            <span class="content">{{ details.closeTime }}</span>
          </div>
          <div class="data-cell">
            <span class="label">报告人</span>
            <span class="content">{{ details.createdFullName }}</span>
          </div>
          <div class="data-cell">
            <span class="label">指派组</span>
            <span class="content">{{ details.assigneeGroupName }}</span>
          </div>
          <div class="data-cell">
            <span class="label">指派技术员</span>
            <span class="content">{{ details.technicianName }}</span>
          </div>
          <div class="data-cell">
            <span class="label">创建时间</span>
            <span class="content">{{ details.createdOn }}</span>
          </div>
          <div class="data-cell">
            <span class="label">已知错误</span>
            <span class="content" :class="{ 'color-red': !details.knownError }">{{ details.knownError ? "是" : "否" }}</span>
          </div>
        </div>
        <!-- <div class="title">拓展信息</div> -->
        <el-tabs v-model="tabName" class="demo-tabs">
          <el-tab-pane label="扩展信息" name="expandInfo">
            <p v-if="formCreateRules.length <= 0" style="font-size: 20px; color: red">暂无相关数据...</p>
            <!-- <ExpandInfo type="problem" :details="details" v-if="formCreateRules.length<=0"></ExpandInfo> -->
            <form-create v-model="formData" v-model:api="formApi" :option="option" :rule="formCreateRules" />
          </el-tab-pane>
          <!-- 附件 -->
          <el-tab-pane label="附件" name="enclosure">
            <EnclosureList
              v-if="tabHistory.indexOf('enclosure') >= 0"
              :eno="details.eno"
              event-type="itsm.problem"
            ></EnclosureList>
          </el-tab-pane>
          <!-- 问题处理 -->
          <el-tab-pane label="问题处理" name="changeApproval">
            <div style="width: 55%; padding: 15px; border: 1px solid #e5e5e5; border-radius: 10px">
              <el-form label-width="80">
                <el-form-item label="">
                  <el-radio-group v-model="problemType" aria-label="label position">
                    <el-radio-button value="symptom">问题细节</el-radio-button>
                    <el-radio-button value="effect">影响</el-radio-button>
                    <el-radio-button value="rootCauses">根本原因</el-radio-button>
                    <el-radio-button value="alternatives">变通方法</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="细节描述" v-if="problemType == 'symptom'">
                  <el-input type="textarea" v-model="problemForm.symptom" :rows="3" placeholder="细节描述" />
                </el-form-item>
                <el-form-item label="影响描述" v-if="problemType == 'effect'">
                  <el-input type="textarea" v-model="problemForm.effect" :rows="3" placeholder="影响描述" />
                </el-form-item>
                <el-form-item label="原因描述" v-if="problemType == 'rootCauses'">
                  <el-input type="textarea" v-model="problemForm.rootCauses" :rows="3" placeholder="原因描述" />
                </el-form-item>
                <el-form-item label="方法描述" v-if="problemType == 'alternatives'">
                  <el-input type="textarea" v-model="problemForm.alternatives" :rows="3" placeholder="方法描述" />
                </el-form-item>
                <el-form-item label="">
                  <el-button type="primary" @click="problemSubmit">保存</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <!-- 解决方案 -->
          <el-tab-pane label="解决方案" name="solution">
            <!-- <div class="table-data-box">
              <div class="data-cell row">
                <span class="label">处理方式编号</span>
                <span class="content">{{ details.offmodeNo }}</span>
              </div>
              <div class="data-cell row">
                <span class="label">处理方式</span>
                <span class="content">{{ details.offmodeName }}</span>
              </div>
              <div class="data-cell row">
                <span class="label">方案描述</span>
                <span class="content" v-html="details.solutions"></span>
              </div>
            </div> -->
            <div style="width: 55%; padding: 15px; border: 1px solid #e5e5e5; border-radius: 10px">
              <el-form label-width="80">
                <!-- <el-form-item label="处理方式">
                  <el-input placeholder="请选手处理方式" />
                </el-form-item> -->
                <el-form-item label="方案描述">
                  <el-input type="textarea" v-model="solutionContent" :rows="3" placeholder="方案描述" />
                </el-form-item>
                <el-form-item label="">
                  <el-button type="primary" @click="solutionSubmit">保存</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <!-- 历史记录 -->
          <el-tab-pane label="历史记录" name="historicalRecords">
            <HistoricalRecordsBox
              v-if="tabHistory.indexOf('historicalRecords') >= 0"
              :eno="details.eno"
              event-type="itsm.problem"
            ></HistoricalRecordsBox>
          </el-tab-pane>
          <!-- 历史邮件 -->
          <el-tab-pane label="历史邮件" name="email">
            <EmailListBox
              v-if="tabHistory.indexOf('email') >= 0"
              :eno="details.eno"
              :request-code="details.requestCode"
            ></EmailListBox>
          </el-tab-pane>
          <el-tab-pane label="关联配置项" name="associationConfig">
            <!-- <AssociationConfigList v-if="tabHistory.indexOf('associationConfig') >= 0" :eno="details.eno"></AssociationConfigList> -->
            <ProTable
              ref="ciProTable"
              row-key="id"
              :indent="20"
              :data="ciList"
              :columns="ciColumns"
              :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
            >
            </ProTable>
          </el-tab-pane>
          <!-- 关联服务 -->
          <el-tab-pane label="关联服务" name="associationServe">
            <!-- <AssociationServicesBox :list="details.listEvent"></AssociationServicesBox> -->
            <ProTable
              ref="serviceDirectoryProTable"
              row-key="id"
              :indent="20"
              :data="serviceDirectoryList"
              :columns="serviceDirectoryColumns"
              :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
            >
            </ProTable>
          </el-tab-pane>
          <!-- 关联请求 -->
          <el-tab-pane label="关联请求" name="associationRequest">
            <AssociationRequestBox
              v-if="tabHistory.indexOf('associationRequest') >= 0"
              :pno="details.eno"
            ></AssociationRequestBox>
          </el-tab-pane>
          <!-- 任务 -->
          <el-tab-pane label="任务" name="task">
            <TaskListBox v-if="tabHistory.indexOf('task') >= 0" :eno="details.eno" event-type="itsm.problem"></TaskListBox>
          </el-tab-pane>
          <!-- 进展及成本 -->
          <el-tab-pane label="进展及成本" name="progressAndCost">
            <CostList v-if="tabHistory.indexOf('progressAndCost') >= 0" :pno="details.eno" event-type="itsm.problem"></CostList>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
    <!-- 标记为已知错误 -->
    <el-dialog
      v-model="knownErrorMask"
      title="标记为已知错误"
      width="500"
      :close-on-click-modal="false"
      v-loading="knownErrorLoading"
    >
      <el-form>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="knownErrorRemark" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="knownErrorMask = false">取消</el-button>
        <el-button type="primary" @click="markKnownErrorSubmit">提交</el-button>
      </template>
    </el-dialog>
    <!-- 问题指派弹窗 -->
    <el-dialog v-model="problemAssignmentMask" :title="optName" width="500" @close="closeZpDialog">
      <div v-loading="loading">
        <el-form label-width="60" :disabled="optName == '开启流程' || optName == '动作-分析完成' || opt == 'other'">
          <el-form-item
            label="技术组"
            v-if="optName != '开启流程' && optName != '动作-分析完成' && optName != '动作-提交评审' && opt != 'other'"
          >
            <!-- <el-cascader v-model="assigneeGroupNo" :options="groupList" :show-all-levels="false" style="width: 100%" /> -->
            <el-input
                style="flex: 1; overflow: hidden"
                v-model="assigneeGroupName"
                placeholder="请选择指派组"
                :readonly="true"
                clearable
            ></el-input>
            <el-button
              style="margin-left: 10px"
              type="primary"
              :icon="Search"
              @click="selectDepartment('filterForm.assigneeGroupNo', '请选择指派组')"
            ></el-button>
          </el-form-item>
          <el-form-item
            label="技术组"
            v-if="optName == '开启流程' || optName == '动作-分析完成' || optName == '动作-提交评审' || opt == 'other'"
          >
            <el-input
              style="flex: 1; overflow: hidden"
              v-model="details.assigneeGroupName"
              placeholder="请选择技术员"
              :readonly="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="技术员">
            <div style="display: flex; width: 100%">
              <el-input style="flex: 1; overflow: hidden" v-model="technicianName" placeholder="请选择技术员" readonly></el-input>
              <el-button style="margin-left: 10px" type="primary" :icon="Search" @click="selectUser"></el-button>
            </div>
          </el-form-item>
        </el-form>
        <el-form label-width="60">
          <el-form-item label="备注">
            <el-input type="textarea" v-model="problemAssignmentForm.remark" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="problemAssignmentMask = false">取消</el-button>
        <el-button type="primary" @click="problemAssignmentSubmit">提交</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="cxzpDialog" title="任务重新指派" width="500">
      <el-form label-width="60">
        <!-- <el-form-item label="技术组">
	      <el-cascader v-model="assigneeGroupNokqlc" :options="groupList" :show-all-levels="false" style="width: 100%" />
	    </el-form-item> -->
        <el-form-item label="技术员">
          <div style="display: flex; width: 100%">
            <el-input
              style="flex: 1; overflow: hidden"
              v-model="technicianNameRwcxzp"
              placeholder="请选择技术员"
              readonly
            ></el-input>
            <el-button
              style="margin-left: 10px"
              type="primary"
              :icon="Search"
              @click="dialogCustomerCreatedByTableVisible = true"
            ></el-button>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="remarkRwcxzp" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cxzpDialog = false">取消</el-button>
        <el-button type="primary" @click="problemRwcxzp">提交</el-button>
      </template>
      <el-dialog title="选择用户" v-model="dialogCustomerCreatedByTableVisible">
        <div :style="{ height: '500px' }">
          <Userselect @send-data="sendCreatedByDataCustomer" :father="fatherValue" />
        </div>
      </el-dialog>
    </el-dialog>
    <!-- 选择技术员 -->
    <SelectUserMask
      ref="selectUserMask"
      title="技术组"
      :group-no="problemAssignmentForm.assigneeGroupNo"
      @change="selectUserChange"
    ></SelectUserMask>
    <!-- 选择部门 -->
    <SelectDepartment ref="selectDepartmentMask" :title="selectDepartmentTitle" @change="departmentChange"></SelectDepartment>
  </div>
</template>

<script setup lang="ts" name="ProblemDetailsMask">
import { ref, watch, reactive } from "vue";

import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";

import ExpandInfo from "@/components/ExpandInfo/index.vue";
import EnclosureList from "@/components/EnclosureList/index.vue";
import TaskListBox from "@/components/TaskListBox/index.vue";
import HistoricalRecordsBox from "@/components/HistoricalRecordsBox/index.vue";
import EmailListBox from "@/components/EmailListBox/index.vue";
import AssociationServicesBox from "@/components/AssociationServicesBox/index.vue";
import AssociationRequestBox from "@/components/AssociationRequestBox/index.vue";
import SelectUserMask from "@/components/SelectUserMask/index.vue";
import CostList from "@/components/CostList/index.vue";
import AssociationConfigList from "@/components/AssociationConfigList/index.vue";
import { findAllClienk, processDetail } from "@/api/modules/common";
import { findProblemById, actionFlow, findAllHistoryRecordByClient, saveComment, saveSolution } from "@/api/modules/problem";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { useUserStore } from "@/stores/modules/user";
import Userselect from "@/views/tools/userSelectbyOrgNo/index.vue";
import { openProcess, assignTask, processHandle, findByIdCategorys, findEventEav } from "@/api/modules/problemManagement";
import { dataDictionaryItemsfindByCode, getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import { findSubCategorysByEvenId, findAttributeList } from "@/api/modules/systemTools";
import formCreate from "@form-create/element-ui"; // 引入 FormCreate
import SelectDepartment from "@/components/SelectDepartment/SelectDepartment.vue";
const userStore = useUserStore();
//扩展信息

const formData = ref({});
const formApi = ref(null);
const formCreateRules = ref<any>([]);
const formCreateRules2 = ref<any>([]);
const option = ref({
  submitBtn: false
});

const kzxx = (categoryNo: string) => {
  console.log("ssssssssssssss");
  console.log(categoryNo);
  findByIdCategorys(categoryNo).then(categoryNoRes => {
    let newcategoryNoRes = JSON.parse(JSON.stringify(categoryNoRes));
    console.log("ssssssssssssssssqqqqqqss");
    console.log(newcategoryNoRes);

    if (formCreateRules.value.length != 0) {
      formCreateRules.value.length = 0;
    }
    // if (dataDictionaryFlagList.value.length != 0) {
    //   dataDictionaryFlagList.value.length = 0;
    // }
    if (newcategoryNoRes.eavId != undefined && newcategoryNoRes.eavId != null)
      findAttributeList(newcategoryNoRes.eavId).then(resAttList => {
        (resAttList as any).forEach(function (element) {
          if (element.attrType == "String") {
            formCreateRules.value.push({
              type: "input",
              field: element.attrName,
              title: element.attrAsName,
              value: "",
              col: {
                span: 10
              }
            });
          }
          if (element.attrType == "Radio") {
            formCreateRules.value.push({
              type: "radio",
              field: element.attrName,
              title: element.attrAsName,
              value: "",
              col: {
                span: 12
              },
              options: [{ value: true, label: element.attrAsName, disabled: false }]
            });
          }
          if (element.attrType == "checkbox") {
            formCreateRules.value.push({
              type: "checkbox",
              field: element.attrName,
              title: element.attrAsName,
              value: "",
              col: {
                span: 10
              },
              options: [{ value: true, label: element.attrAsName, disabled: false }]
            });
          }
          if (element.attrType == "Double") {
            formCreateRules.value.push({
              type: "InputNumber",
              field: element.attrName,
              title: element.attrAsName,
              value: "",
              col: {
                span: 10
              },
              props: {
                precision: 3
              }
            });
          }
          if (element.attrType == "Integer") {
            formCreateRules.value.push({
              type: "InputNumber",
              field: element.attrName,
              title: element.attrAsName,
              value: "",
              col: {
                span: 10
              },
              props: {
                precision: 0
              }
            });
          }
          if (element.attrType == "Date") {
            formCreateRules.value.push({
              type: "DatePicker",
              field: element.attrName,
              title: element.attrAsName,
              value: "",
              col: {
                span: 10
              },
              props: {
                type: "datetime",
                placeholder: "请选择日期"
              }
            });
          }
          if (element.attrType == "Lob") {
            formCreateRules.value.push({
              type: "input",
              field: element.attrName,
              title: element.attrAsName,
              value: "",
              col: {
                span: 10
              },
              props: {
                type: "textarea "
              }
            });
          }
          if (element.attrType == "DataDictionaray") {
            let optionList = [];
            //优先级priority
            dataDictionaryItemsfindByCode(element.attrdataDictionary).then(res => {
              (res as any).forEach(function (element) {
                element["lable"] = element["dname"];
                element["value"] = element["dname"];
              });
              optionList = res as any;
              formCreateRules.value.push({
                type: "select",
                field: element.attrName,
                title: element.attrAsName,
                value: "",
                col: {
                  span: 10
                },
                options: optionList
              });
              // let dataDictionaryFlagListObj = {
              //   id: element.attrName,
              //   attrdataDictionary: element.attrdataDictionary,
              //   dataList: optionList
              // };
              // dataDictionaryFlagList.value.push(dataDictionaryFlagListObj);
            });
          }
        });
      });

    // findSubCategorysByEvenId(categoryNoRes.eventId).then(res => {
    //   if (res.toString() == "true") {

    //   }
    // });
  });
};

//扩展信息结束

//流程重新开始
const reStart = () => {
  ElMessageBox.prompt("请输入备注", "重新开始", {
    confirmButtonText: "确认",
    cancelButtonText: "取消"
  })
    .then(({ value }) => {
      actionFlow({
        "problemDTO.lastUpdater": userStore.username,
        "problemDTO.actionFlag": "reopen",
        "problemDTO.eno": details.value.eno,
        "problemDTO.pid": details.value.pid,
        "problemDTO.remark": value
      })
        .then(res => {
          ElMessage.success("提交成功");
          getData();
        })
        .catch(err => {
          console.log("err");
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Input canceled"
      });
    });
  console.log("restart");
};

//流程重新开始结束

//开启流程
const kqlc = ref(false);

const assigneeGroupNokqlc = ref("");
const technicianNamekqlc = ref("");
const optName = ref("");
const showkqlc = () => {
  opt.value = "kqlc";
  optName.value = "开启流程";

  problemAssignmentForm.technicianNo = details.value.technicianNo;
  technicianName.value = details.value.technicianName;
  problemAssignmentForm.assigneeGroupNo = details.value.assigneeGroupNo;
  problemAssignmentMask.value = true;

  // 指派组
  findAllClienk({
    companyNo: userStore.userInfo.companyNo,
    parentOrgNo: 0,
    _: new Date().getTime()
  }).then((res: any) => {
    let list = flattenAttr(res.children);
    list.forEach((item: any) => {
      item.label = item.orgName;
      item.value = item.orgNo;
      if (item.children) {
        item.children.forEach(vo => {
          vo.label = vo.orgName;
          vo.value = vo.orgNo;
          if (vo.children) {
            vo.children.forEach(v => {
              v.label = v.orgName;
              v.value = v.orgNo;
            });
          }
        });
      }
    });
    groupList.value = list;
  });
};
// 选择部门
const selectDepartmentType = ref("");
const selectDepartmentTitle = ref("");
const selectDepartmentMask = ref();
const assigneeGroupName = ref("");
const selectDepartment = (type: string, title: string) => {
  selectDepartmentType.value = type;
  selectDepartmentTitle.value = title;
  selectDepartmentMask.value?.open();
};
const departmentChange = e => {
  switch (selectDepartmentType.value) {
    // case "filterForm.requestorOrgNo":
    //   requestorOrgName.value = e.orgName;
    //   filterForm.requestorOrgNo = e.orgNo;
    //   break;
    case "filterForm.assigneeGroupNo":
    problemAssignmentForm.assigneeGroupNo = e.orgNo;
    // problemAssignmentForm.groupName = e.orgName;
      assigneeGroupName.value = e.orgName;
      break;
    // case "conditionForm.propValue":
    //   conditionForm.propDisplayValue = e.orgName;
    //   conditionForm.propValue = e.orgNo;
    //   break;
    default:
      break;
  }
};
//开启流程
//-----------任务重新指派开始
const fatherValue = ref({ orgNo: 1 });
const dialogCustomerCreatedByTableVisible = ref(false); //创建人
const technicianNameRwcxzp = ref("");
const technicianNoRwcxzp = ref("");
const remarkRwcxzp = ref("");
const cxzpDialog = ref(false);
// 显示任务重新指派
const showTaskCxzp = () => {
  cxzpDialog.value = true;
  technicianNoRwcxzp.value = details.value.technicianNo;
  technicianNameRwcxzp.value = details.value.technicianName;
};
//用户选择子组件弹窗回调方法
const sendCreatedByDataCustomer = (data: any) => {
  technicianNoRwcxzp.value = data.userId;
  technicianNameRwcxzp.value = data.fullName;
  dialogCustomerCreatedByTableVisible.value = false;
};
const processDetailData = ref<any>({});
//执行工单流程
const outcome = ref("");
const otherOutcomeName = ref("");
const processOutcome = (e: string) => {
  if (e === "分析完成") {
    opt.value = "fxwc";
    optName.value = "动作-分析完成";
    problemAssignmentForm.technicianNo = details.value.technicianNo;
    technicianName.value = details.value.technicianName;
    problemAssignmentForm.assigneeGroupNo = details.value.assigneeGroupNo;
    problemAssignmentMask.value = true;
    // showProcessingCompletedMask();
  } else if (e === "提交评审") {
    opt.value = "tjps";
    optName.value = "动作-提交评审";
    problemAssignmentForm.technicianNo = details.value.technicianNo;
    technicianName.value = details.value.technicianName;
    problemAssignmentForm.assigneeGroupNo = details.value.assigneeGroupNo;
    problemAssignmentMask.value = true;
  } else {
    opt.value = "other";
    optName.value = "动作-" + e;
    otherOutcomeName.value = e;
    problemAssignmentForm.technicianNo = details.value.technicianNo;
    technicianName.value = details.value.technicianName;
    problemAssignmentForm.assigneeGroupNo = details.value.assigneeGroupNo;
    problemAssignmentMask.value = true;
  }
};
// 提交任务重新指派
const problemRwcxzp = () => {
  if (!technicianNoRwcxzp.value) {
    ElMessage({
      customClass: "customMsgCls",
      message: "请选择技术员",
      type: "error"
    });

    return false;
  }
  loading.value = true;
  processDetail(details.value.pid)
    .then(res => {
      let taskId = res[0].flowTaskDTO[0].taskId;
      console.log(res[0]);
      assignTask({
        "processHandleDTO.pid": details.value.pid,
        "processHandleDTO.taskId": taskId,
        "processHandleDTO.eno": details.value.eno,
        "processHandleDTO.module": "problem",
        "processHandleDTO.operator": userStore.username,
        "processHandleDTO.handleType": "TaskReAssigne",
        "processHandleDTO.assignType": "autoAssignee",
        "processHandleDTO.allowUseDynamicAssignee": "false",
        "processHandleDTO.allowUseVariablesAssignee": "false",
        "processHandleDTO.assigneeNo": technicianNoRwcxzp.value,
        "processHandleDTO.remark": remarkRwcxzp.value
      })
        .then(() => {
          loading.value = false;
          problemAssignmentMask.value = false;
          dialogVisible.value = false;
          cxzpDialog.value = false;
          ElMessage.success("重新指派成功");
          getData();
        })
        .catch(err => {
          loading.value = false;
        });
    })
    .catch(err => {
      ElMessage.success("重新指派失败");
      cxzpDialog.value = false;
    });
};

//-------------任务重新指派结束
const serviceDirectoryProTable = ref<ProTableInstance>();
const serviceDirectoryList = ref<any>([]);

const serviceDirectoryColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "id", label: "ID", sortable: true },
  { prop: "cname", label: "服务名称", sortable: true, width: 260 }
]);

//关联配置项开始
const ciProTable = ref<ProTableInstance>();
const ciList = ref<any>([]);
const ciColumns = reactive<ColumnProps<resCIList>[]>([
  { prop: "cino", label: "固定资产编号", sortable: true },
  { prop: "ciname", label: "名称", sortable: true, width: 260 },
  { prop: "categoryName", label: "分类", sortable: true, width: 260 },
  { prop: "status", label: "状态", sortable: true, width: 260 }
]);
export interface resCIList {
  ciname: string;
  cino: string;
  categoryName: string;
  categoryNo: string;
  status: string;
  ciId: number;
  attachmentStr: string;
  fileName: string;
  beginTime: string;
  companyName: string;
  companyNo: number;
  contractName: string;
  contractNo: number;
  dataFlag: number;
  description: string;
  dialect: string;
  endTime: string;
  finishTime: number;
  flagName: string;
  lastUpdater: string;
  packageName: string;
  respondTime: number;
  ruleName: string;
  ruleNo: number;
  rulePackageNo: number;
  salience: number;
  showFinishTime: string;
  showRespondTime: string;
  beforeOrAfter: boolean;
  beforeOrAfterStr: string;
  timeStr: string;
}
interface TreeNode {
  attr?: Record<string, any>; // attr 是一个可选的对象，键是字符串，值是任意类型
  children?: TreeNode[]; // children 是一个可选的 TreeNode 数组
}

function flattenAttr(nodes: TreeNode[]): TreeNode[] {
  return nodes.map(node => {
    const result: TreeNode = {
      children: node.children ? flattenAttr(node.children) : []
    };

    if (node.attr) {
      // 使用对象解构和展开运算符将 attr 的内容复制到 result 对象中
      // 注意：这里会覆盖 result 对象中可能已存在的同名属性（如果有的话）
      Object.assign(result, node.attr);
    }

    // 由于我们已经明确设置了 children，所以这里不需要再检查 undefined
    return result;
  });
}

const dialogVisible = ref(false);
const details = ref<any>({});
const loading = ref(false);
const tabName = ref("expandInfo");
const tabHistory = ref<string[]>([]); // tab切换历史
const groupList = ref<any[]>([]);

// 问题指派
const problemAssignmentForm = reactive({
  assigneeGroupNo: "",
  technicianNo: "",
  remark: ""
});
const assigneeGroupNo = ref("");
const technicianName = ref("");
watch(
  () => assigneeGroupNo.value,
  val => {
    if (val.length > 0) {
      problemAssignmentForm.assigneeGroupNo = val[2];
    } else {
      problemAssignmentForm.assigneeGroupNo = "";
    }
  }
);
const problemAssignmentMask = ref(false);
// 显示问题指派弹窗
const showProblemAssignmentMask = () => {
  opt.value = "wtzp";
  optName.value = "问题指派";
  problemAssignmentMask.value = true;
  // 指派组
  // findAllClienk({
  //   companyNo: userStore.userInfo.companyNo,
  //   parentOrgNo: 0,
  //   _: new Date().getTime()
  // }).then((res: any) => {
  //   let list = flattenAttr(res.children);
  //   list.forEach((item: any) => {
  //     item.label = item.orgName;
  //     item.value = item.orgNo;
  //     if (item.children) {
  //       item.children.forEach(vo => {
  //         vo.label = vo.orgName;
  //         vo.value = vo.orgNo;
  //         if (vo.children) {
  //           vo.children.forEach(v => {
  //             v.label = v.orgName;
  //             v.value = v.orgNo;
  //           });
  //         }
  //       });
  //     }
  //   });
  //   groupList.value = list;
  // });
};

// 选择技术员弹窗
const selectUserMask = ref();
const selectUser = () => {
  if (!problemAssignmentForm.assigneeGroupNo) {
    ElMessage({
      customClass: "customMsgCls",
      message: "请选择技术组",
      type: "error"
    });

    return false;
  }
  selectUserMask.value?.open();
};
// 选择技术员
const selectUserChange = e => {
  problemAssignmentForm.technicianNo = e.userId;
  technicianName.value = e.fullName;
};
const problemAssignmentLoading = ref(false);
const opt = ref("");
// 提交问题指派
const problemAssignmentSubmit = () => {
  if (!problemAssignmentForm.assigneeGroupNo) {
    ElMessage({
      customClass: "customMsgCls",
      message: "请选择技术组",
      type: "error"
    });
    return false;
  }
  if (!problemAssignmentForm.technicianNo) {
    ElMessage({
      customClass: "customMsgCls",
      message: "请选择技术员",
      type: "error"
    });
    return false;
  }

  if (opt.value == "kqlc") {
    loading.value = true;
    console.log("开启流程");
    openProcess({
      "processHandleDTO.eno": details.value.eno,
      "processHandleDTO.operator": userStore.username,
      "processHandleDTO.assignType": "autoAssignee",
      "processHandleDTO.nextActivityType": "task",
      "processHandleDTO.allowUseDynamicAssignee": "false",
      "processHandleDTO.approverTask": "false",
      "processHandleDTO.module": "problem",
      "processHandleDTO.leaderNum": "0",
      "processHandleDTO.allowUseVariablesAssignee": "false",
      "processHandleDTO.variablesAssigneeGroupNo": "0",
      "processHandleDTO.mailHandlingProcess": "false",
      "processHandleDTO.remark": problemAssignmentForm.remark,
      "processHandleDTO.groupNo": problemAssignmentForm.assigneeGroupNo,
      "processHandleDTO.assigneeNo": problemAssignmentForm.technicianNo,
      "processHandleDTO.approverResult": "true"
    })
      .then(() => {
        loading.value = false;
        problemAssignmentMask.value = false;
        dialogVisible.value = false;
        ElMessage.success("开启成功");
        getData();
      })
      .catch(err => {
        loading.value = false;
      });
  } else if (opt.value == "fxwc") {
    loading.value = true;
    processHandle({
      "processHandleDTO.pid": details.value.pid,
      "processHandleDTO.taskId": processDetailData.value.taskId,
      "processHandleDTO.eno": details.value.eno,
      "processHandleDTO.operator": userStore.username,
      "processHandleDTO.assignType": "autoAssignee",
      "processHandleDTO.outcome": "分析完成",
      "processHandleDTO.nextActivityType": "task",
      "processHandleDTO.allowUseDynamicAssignee": "false",
      "processHandleDTO.flowActivityId": processDetailData.value.flowActivityDTO.id,
      "processHandleDTO.approverTask": "false",
      "processHandleDTO.module": "problem",
      "processHandleDTO.variablesAssigneeType": "",
      "processHandleDTO.leaderNum": 0,
      "processHandleDTO.allowUseVariablesAssignee": "false",
      "processHandleDTO.variablesAssigneeGroupNo": 0,
      "processHandleDTO.variablesAssigneeGroupName": "",
      "processHandleDTO.mailHandlingProcess": "false",
      "processHandleDTO.activityName": processDetailData.value.flowActivityDTO.activityName,
      "processHandleDTO.remark": problemAssignmentForm.remark,
      "processHandleDTO.groupNo": problemAssignmentForm.assigneeGroupNo,
      "processHandleDTO.assigneeNo": problemAssignmentForm.technicianNo,
      "processHandleDTO.approversMemberSet": "",
      "processHandleDTO.approverResult": "true"
    })
      .then(() => {
        loading.value = false;
        problemAssignmentMask.value = false;
        dialogVisible.value = false;
        cxzpDialog.value = false;
        ElMessage.success("分析完成成功");
        getData();
      })
      .catch(err => {
        loading.value = false;
      });
  } else if (opt.value == "tjps") {
    if (!details.value.psolutions) {
      ElMessage({
        customClass: "customMsgCls",
        message: "提交前请填写解决方案",
        type: "error"
      });
      return false;
    }
    loading.value = true;
    processHandle({
      "processHandleDTO.pid": details.value.pid,
      "processHandleDTO.taskId": processDetailData.value.taskId,
      "processHandleDTO.eno": details.value.eno,
      "processHandleDTO.operator": userStore.username,
      "processHandleDTO.assignType": "autoAssignee",
      "processHandleDTO.outcome": "提交评审",
      "processHandleDTO.nextActivityType": "task",
      "processHandleDTO.allowUseDynamicAssignee": "false",
      "processHandleDTO.flowActivityId": processDetailData.value.flowActivityDTO.id,
      "processHandleDTO.approverTask": "false",
      "processHandleDTO.module": "problem",
      "processHandleDTO.variablesAssigneeType": "",
      "processHandleDTO.leaderNum": 0,
      "processHandleDTO.allowUseVariablesAssignee": "false",
      "processHandleDTO.variablesAssigneeGroupNo": 0,
      "processHandleDTO.variablesAssigneeGroupName": "",
      "processHandleDTO.mailHandlingProcess": "false",
      "processHandleDTO.activityName": processDetailData.value.flowActivityDTO.activityName,
      "processHandleDTO.remark": problemAssignmentForm.remark,
      "processHandleDTO.groupNo": problemAssignmentForm.assigneeGroupNo,
      "processHandleDTO.assigneeNo": problemAssignmentForm.technicianNo,
      "processHandleDTO.approversMemberSet": "",
      "processHandleDTO.approverResult": "true"
    })
      .then(() => {
        loading.value = false;
        problemAssignmentMask.value = false;
        dialogVisible.value = false;
        cxzpDialog.value = false;
        ElMessage.success("提交评审成功");
        getData();
      })
      .catch(err => {
        loading.value = false;
      });
  } else if (opt.value == "other") {
    loading.value = true;
    processHandle({
      "processHandleDTO.pid": details.value.pid,
      "processHandleDTO.taskId": processDetailData.value.taskId,
      "processHandleDTO.eno": details.value.eno,
      "processHandleDTO.operator": userStore.username,
      "processHandleDTO.assignType": "autoAssignee",
      "processHandleDTO.outcome": otherOutcomeName.value,
      "processHandleDTO.nextActivityType": "task",
      "processHandleDTO.allowUseDynamicAssignee": "false",
      "processHandleDTO.flowActivityId": processDetailData.value.flowActivityDTO.id,
      "processHandleDTO.approverTask": "false",
      "processHandleDTO.module": "problem",
      "processHandleDTO.variablesAssigneeType": "",
      "processHandleDTO.leaderNum": 0,
      "processHandleDTO.allowUseVariablesAssignee": "false",
      "processHandleDTO.variablesAssigneeGroupNo": 0,
      "processHandleDTO.variablesAssigneeGroupName": "",
      "processHandleDTO.mailHandlingProcess": "false",
      "processHandleDTO.activityName": processDetailData.value.flowActivityDTO.activityName,
      "processHandleDTO.remark": problemAssignmentForm.remark,
      "processHandleDTO.groupNo": problemAssignmentForm.assigneeGroupNo,
      "processHandleDTO.assigneeNo": problemAssignmentForm.technicianNo,
      "processHandleDTO.approversMemberSet": "",
      "processHandleDTO.approverResult": "true"
    })
      .then(() => {
        loading.value = false;
        problemAssignmentMask.value = false;
        dialogVisible.value = false;
        cxzpDialog.value = false;
        ElMessage.success(otherOutcomeName.value + "成功");
        getData();
      })
      .catch(err => {
        loading.value = false;
      });
  } else {
    loading.value = true;
    findAllHistoryRecordByClient({
      "problemDTO.currentUser": userStore.username,
      "problemDTO.lastUpdater": userStore.username,
      "problemDTO.eno": details.value.eno,
      "problemDTO.pid": details.value.pid,
      "problemDTO.assigneeGroupNo": problemAssignmentForm.assigneeGroupNo,
      "problemDTO.technicianNo": problemAssignmentForm.technicianNo,
      "problemDTO.remark": problemAssignmentForm.remark
    })
      .then(() => {
        loading.value = false;
        problemAssignmentMask.value = false;
        dialogVisible.value = false;
        ElMessage.success("提交成功");
        getData();
      })
      .catch(err => {
        loading.value = false;
      });
  }
};

// 标记已知错误弹窗
const knownErrorMask = ref(false);
const markKnownError = () => {
  knownErrorRemark.value = "";
  knownErrorMask.value = true;
};

const knownErrorRemark = ref("");
const knownErrorLoading = ref(false);

const markKnownErrorSubmit = () => {
  knownErrorLoading.value = true;
  actionFlow({
    "problemDTO.knownError": 1,
    "problemDTO.lastUpdater": "",
    "problemDTO.actionFlag": "knownError",
    "problemDTO.eno": details.value.eno,
    "problemDTO.pid": details.value.pid,
    "problemDTO.remark": knownErrorRemark.value
  })
    .then(res => {
      knownErrorLoading.value = false;
      knownErrorRemark.value = "";
      knownErrorMask.value = false;
      ElMessage.success("提交成功");
      getData();
    })
    .catch(err => {
      knownErrorLoading.value = false;
    });
};

// 取消已知错误
const cancelKnownError = () => {
  ElMessageBox.confirm("确定要取消已知错误标记？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      loading.value = true;
      // 取消已知错误
      actionFlow({
        "problemDTO.knownError": 0,
        "problemDTO.lastUpdater": "",
        "problemDTO.actionFlag": "knownError",
        "problemDTO.eno": details.value.eno,
        "problemDTO.pid": details.value.pid,
        "problemDTO.remark": ""
      })
        .then(() => {
          loading.value = false;
          ElMessage.success("操作成功");
          getData();
        })
        .catch(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // cancel operation
    });
};

// 问题处理
const problemType = ref("symptom");
const problemForm = reactive({
  symptom: "",
  effect: "",
  rootCauses: "",
  alternatives: ""
});
// 保存问题处理方法
const problemSubmit = () => {
  if (!problemForm.symptom) {
    ElMessage({
      customClass: "customMsgCls",
      message: "请输入问题细节",
      type: "error"
    });

    return false;
  }
  if (!problemForm.effect) {
    ElMessage({
      customClass: "customMsgCls",
      message: "请输入影响",
      type: "error"
    });

    return false;
  }
  if (!problemForm.rootCauses) {
    ElMessage({
      customClass: "customMsgCls",
      message: "请输入根本原因",
      type: "error"
    });

    return false;
  }
  if (!problemForm.alternatives) {
    ElMessage({
      customClass: "customMsgCls",
      message: "请输入变通方法",
      type: "error"
    });

    return false;
  }
  loading.value = true;
  let success_num = 0;
  let timeout_num = 0;
  for (const key in problemForm) {
    if (Object.prototype.hasOwnProperty.call(problemForm, key)) {
      const element = problemForm[key];
      setTimeout(() => {
        saveComment(key, {
          "commentDTO.eno": details.value.eno,
          "commentDTO.lastUpdater": userStore.username,
          "commentDTO.remark": element,
          "commentDTO.attachmentStr": ""
        })
          .then(() => {
            success_num++;
            if (success_num == 4) {
              loading.value = false;
              ElMessage.success("保存成功");
            }
          })
          .catch(() => {
            loading.value = false;
            if (key == "symptom") {
              ElMessage.error("问题细节保存失败");
            } else if (key == "effect") {
              ElMessage.error("影响保存失败");
            } else if (key == "rootCauses") {
              ElMessage.error("根本原因保存失败");
            } else if (key == "alternatives") {
              ElMessage.error("变通方法保存失败");
            }
          });
      }, timeout_num);
      timeout_num += 600;
    }
  }
};

// 解决方案
const solutionContent = ref("");
// 提交解决方案
const solutionSubmit = () => {
  if (!solutionContent.value) {
    ElMessage({
      customClass: "customMsgCls",
      message: "请输入方案描述",
      type: "error"
    });

    return false;
  }
  loading.value = true;
  saveSolution({
    eno: details.value.eno,
    "knowledgeDTO.lastUpdater": userStore.username,
    "knowledgeDTO.title": details.value.etitle,
    "knowledgeDTO.content": solutionContent.value
  })
    .then(() => {
      loading.value = false;
      ElMessage.success("保存成功");
      getData();
    })
    .catch(() => {
      loading.value = false;
    });
};

// 获取详情
const getData = () => {
  findProblemById({
    eno: details.value.eno,
    random: new Date().getTime()
  })
    .then((res: any) => {
      loading.value = false;
      details.value = {
        ...details.value,
        ...res
      };
      console.log("ddddddddddddddddddd");
      //资产
      ciList.value = details.value.relatedCIS;
      //服务
      let serviceDirectoryNames = details.value.serviceDirectoryNames == undefined ? [] : details.value.serviceDirectoryNames;
      let serviceDirectoryNos = details.value.serviceDirectoryNos == undefined ? [] : details.value.serviceDirectoryNos;
      for (let i = 0; i < serviceDirectoryNames.length; i++) {
        let tmpservice = {
          id: serviceDirectoryNos[i],
          cname: serviceDirectoryNames[i]
        };
        serviceDirectoryList.value.push(tmpservice);
      }
      // 问题处理
      if (details.value.symptomDTO) {
        problemForm.symptom = details.value.symptomDTO.remark;
      }
      if (details.value.effectsDTO) {
        problemForm.effect = details.value.effectsDTO.remark;
      }
      if (details.value.rootCausesDTO) {
        problemForm.rootCauses = details.value.rootCausesDTO.remark;
      }
      if (details.value.alternativesDTO) {
        problemForm.alternatives = details.value.alternativesDTO.remark;
      }
      // 解决方案222222
      solutionContent.value = res.psolutions ? res.psolutions.remark : "";
      fatherValue.value.orgNo = details.value.assigneeGroupNo;
      // 获取流程详情
      if (res.pid) {
        processDetail(res.pid).then((res: any) => {
          if (res.length > 0) {
            processDetailData.value = res[0].flowTaskDTO[0];
            console.log("processDetailData", processDetailData.value);
          } else {
            processDetailData.value = {};
          }
        });
      } else {
        processDetailData.value = {};
      }
      //扩展信息
      kzxx(details.value.categoryNo);
      findEventEav(details.value.eno).then(reseav => {
        if (reseav != null) {
          // let attrVals = newParams.attrVals == undefined ? {} : newParams.attrVals;
          let attrVals = reseav;
          setTimeout(() => {
            Object.keys(attrVals).forEach(key => {
              Object.keys(formData.value).forEach(key2 => {
                if (`${key}` == `${key2}`) {
                  if (`${attrVals[key]}` == "true") {
                    formData.value[`${key2}`] = true;
                  } else {
                    formData.value[`${key2}`] = `${attrVals[key]}`;
                  }
                }
              });
            });
          }, 2200);
        }
      });
    })
    .catch(() => {
      loading.value = false;
    });
};

const open = (item: any) => {
  details.value = item;
  tabName.value = "expandInfo";
  tabHistory.value = [];
  dialogVisible.value = true;
  loading.value = true;
  getData();
  // 重置问题指派弹窗输入框
  problemAssignmentForm.assigneeGroupNo = "";
  problemAssignmentForm.technicianNo = "";
  problemAssignmentForm.remark = "";
  // 已知错误备注
  knownErrorRemark.value = "";
};

watch(tabName, val => {
  tabHistory.value.push(val);
});

defineExpose({
  open
});
// 关闭问题指派弹窗
const closeZpDialog = () => {
  problemAssignmentForm.assigneeGroupNo = "";
  problemAssignmentForm.technicianNo = "";
  problemAssignmentForm.remark = "";
  assigneeGroupName.value = "";
  technicianName.value = "";
};
</script>

<style lang="scss" scoped>
.btns {
  margin-bottom: 10px;
}
.title {
  margin-bottom: 10px;
  font-weight: bold;
}
.color-red {
  color: #ff0000;
}
.customMsgCls {
  z-index: 20010 !important;
}
</style>
